package sns.action;

import java.util.Date;

import org.springframework.transaction.annotation.Transactional;

import sns.bean.User;
import sns.dao.UserDao;
import sns.service.UserService;
import sns.util.Encrypt;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class RegisterAction extends ActionSupport {

	// service and dao
	private UserDao userDao;
	private UserService userService;
	// parameters
	private String username;
	private String nickname;
	private String gender;
	private String pwd;
	private String comefrom;
	private Double coordinateX;
	private Double coordinateY;
	// return value
	/*
	 * error type: 1 = 已存在的用户
	 */
	private Integer errorType;
	private String errorMessage;
	private Integer regSuccess;

	private User user;

	@Transactional
	public String execute() {
		// TODO check validation

		// check if the nick name is username

		user = new User();
		user.setUsername(username);
		user.setNickname(nickname);
		user.setGender(gender);
		System.out.println("I register the password and encrypt as "
				+ Encrypt.encrypt(pwd));
		System.out.println("xCoordinate " + coordinateX);
		user.setPassword(Encrypt.encrypt(pwd));
		user.setComefrom(comefrom);
		user.setAvatar("default.png");
		user.setRegtime(new Date());
		user.setxCoordinate(coordinateX);
		user.setyCoordinate(coordinateY);

		if (userService.findByUsername(username) != null) {
			errorType = 1;
			errorMessage = "该用户名已经存在";
			return Action.ERROR;
		}

		regSuccess = 1;
		userDao.save(user);
		return Action.SUCCESS;
	}

	public Integer getErrorType() {
		return errorType;
	}

	public String getErrorMessage() {
		return errorMessage;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setComefrom(String comefrom) {
		this.comefrom = comefrom;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public User getUser() {
		return user;
	}

	public Integer getRegSuccess() {
		return regSuccess;
	}

	public void setRegSuccess(Integer regSuccess) {
		this.regSuccess = regSuccess;
	}

	public Double getCoordinateX() {
		return coordinateX;
	}

	public void setCoordinateX(Double coordinateX) {
		this.coordinateX = coordinateX;
	}

	public Double getCoordinateY() {
		return coordinateY;
	}

	public void setCoordinateY(Double coordinateY) {
		this.coordinateY = coordinateY;
	}

}
